package com.bonana.backend.controller;

import com.alibaba.fastjson.JSON;
import com.bonana.core.entity.mybatis.Platform;
import com.bonana.core.form.PlatformForm;
import com.bonana.core.result.Response;
import com.bonana.core.result.ResponseCode;
import com.bonana.core.services.UtilsService;
import com.bonana.core.utils.FileInfo;
import com.bonana.core.utils.ImageScaleUtil;
import com.bonana.core.utils.OssUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

/**
 * Created by Administrator on 2016/7/12.
 */
@Controller
@RequestMapping(value="common")
public class CommonControler {
    @Autowired
    UtilsService utilsService;
    @RequestMapping(value="platform")
    public String Platform(Model model) {
        List<Platform> platforms = utilsService.getPlatform();
        model.addAttribute("platforms", platforms);
        return "common/platform";
    }

    @RequestMapping(value="saveplatform")
    @ResponseBody
    public Response SavePlatform(PlatformForm form) {
        if (1== utilsService.SavePlatForm(form)) {
            return new Response(ResponseCode.SUCC);
        } else {
            return new Response(ResponseCode.ERROR);
        }
    }

    @RequestMapping("/delplatform")
    @ResponseBody
    public Response delPlatform(Integer platformId) {
        int ret = utilsService.RemovePlatform(platformId);
        if (ret == 1) {
            return new Response(ResponseCode.SUCC);
        } else {
            return new Response(ResponseCode.ITEM_NOT_FOUND);
        }
    }

    @RequestMapping(value = "queryPlatformById")
    @ResponseBody
    public Platform QueryPlatformById(Integer platformId) {
        return utilsService.getPlatFormById(platformId);
    }

    @ResponseBody
    @RequestMapping("upload")
    public FileInfo uploadFile(@RequestParam(required = false, defaultValue = "0") Integer thumbnail, MultipartFile file) {
        if (file==null) {
            return null;
        }
        FileInfo fileInfo =  OssUtils.putFile(file);
        if(thumbnail == 1) {
            try {
                String fileSuffix = OssUtils.getSuffixByFilename(file.getOriginalFilename());
                fileInfo.setThumbnailUrl(ImageScaleUtil.resizeImage(file.getInputStream(), fileSuffix, 360, 360));
            } catch (IOException e) {
                fileInfo.setThumbnailUrl(fileInfo.getUrl());
                e.printStackTrace();
            }
        }
        return fileInfo;
    }
}
